package org.lex.swt.size;

import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Menu;
import org.lex.swt.WindowState;

public class WindowUtils {
	public static void popup(SashForm sash, Control widget) {
		MenuManager popupMenu = new MenuManager();
		for (WindowState s : WindowState.values()) {
			popupMenu.add(new WindowStateAction(sash, s));
		}
		Menu menu = popupMenu.createContextMenu(widget);
		widget.setMenu(menu);
	}

	private static class WindowStateAction extends Action {
		private final SashForm sash;
		private WindowState state;
		private int[] weightsBak = null;

		public WindowStateAction(SashForm sash, WindowState initState) {
			this.sash = sash;
			this.state = initState;
			this.setText(state.name());
		}

		public void run() {
			if (null == weightsBak) {
				this.weightsBak = sash.getWeights();
			}
			int[] weights = new int[2];
			switch (state) {
			case MAX:
				weights[0] = weightsBak[0] + weightsBak[1];
				weights[1] = 0;
				break;
			case MIN:
				weights[0] = 0;
				weights[1] = weightsBak[0] + weightsBak[1];
				break;
			case RESTORE:
				weights = weightsBak;
				break;
			}
			sash.setWeights(weights);
			this.weightsBak = sash.getWeights();
		}
	}
}
